package icu.cocoon.game.service.impl;

import icu.cocoon.dao.base.BaseService;
import icu.cocoon.game.entity.Pinyin;
import icu.cocoon.game.entity.Proverb;
import icu.cocoon.game.entity.ProverbPinyin;
import icu.cocoon.game.mapper.ProverbMapper;
import icu.cocoon.game.service.PinyinService;
import icu.cocoon.game.service.ProverbPinyinService;
import icu.cocoon.game.service.ProverbService;
import icu.cocoon.game.util.PinyinUtil;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Cocoon
 * @since 2020-07-07
 */
@Service
public class ProverbServiceImpl extends BaseService<ProverbMapper, Proverb> implements ProverbService {

  @Resource
  private PinyinService pinyinService;
  @Resource
  private ProverbPinyinService proverbPinyinService;

  @Override
  public List<Proverb> searchByWord(String word){
    return getMapper().selectByWord(word);
  }

  @Override
  public List<Proverb> searchByPinyin(String pinyin) {
    return getMapper().selectByPinyin(pinyin);
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public int create(Proverb entity) {
    super.create(entity);
    List<Set<String>> setList = PinyinUtil.getPinyin(entity.getWord());
    for (int i = 0; i < setList.size(); i++) {
      for (String s : setList.get(i)) {
        String pinyinString = s.substring(0,s.length()-1);
        Integer tone = Integer.valueOf(s.substring(s.length()-1));
        if (pinyinService.existByPinyinAndTone(pinyinString,tone)){
          continue;
        }
        Pinyin pinyin = new Pinyin();
        pinyin.setPinyin(pinyinString);
        pinyin.setTone(tone);
        pinyinService.create(pinyin);
        ProverbPinyin proverbPinyin = new ProverbPinyin();
        proverbPinyin.setProverbId(entity.getId());
        proverbPinyin.setPinyinId(pinyin.getId());
        proverbPinyin.setIndexNumber(i);
        proverbPinyinService.create(proverbPinyin);
      }
    }
    return 0;
  }
}
